package cn.zlg.common.datadump.service.impl;

import cn.zlg.common.datadump.annotation.DataDumpEntity;
import cn.zlg.common.datadump.bean.DataDumpDef;
import cn.zlg.common.datadump.condition.QueryCondtionDef;
import cn.zlg.common.datadump.service.DataDumpDefRegistry;
import org.apache.shiro.util.Assert;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class DefaultDataDumpDefRegistry implements DataDumpDefRegistry {

    private Map<String, DataDumpDef> registerMap = new HashMap<>();

    @Override
    public void register(Class defClass, DataDumpEntity annotation) throws IllegalAccessException, InstantiationException {
        String name = annotation.name();
        Assert.hasLength(name,
                String.format("类%s的%s注解没有指定名称", defClass.getName(), annotation.getClass().getSimpleName()));
        Assert.isTrue(!registerMap.containsKey(name), String.format("类%s的注解名称%s已存在", defClass.getName(), name));
        Class<? extends QueryCondtionDef> conditionDef = null;
        if (annotation.exportQueryConditions() != QueryCondtionDef.class) {
            conditionDef = annotation.exportQueryConditions();
        }
        registerMap.put(name,
                new DataDumpDef(defClass, annotation, conditionDef == null ? null : conditionDef.newInstance()));
    }

    @Override
    public DataDumpDef getDefinitionByHandler(String handler) {
        return registerMap.get(handler);
    }

    @Override
    public DataDumpEntity findAnnotationByQEntityType(Class clazz) {
        for(Map.Entry<String, DataDumpDef> e : registerMap.entrySet()) {
            if(e.getValue().annotation.entity().equals(clazz)){
                return e.getValue().annotation;
            }
        }
        return null;
    }

    @Override
    public void clear() {
        registerMap.clear();
    }
}
